﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace LogAnalytics
{
    public partial class MainForm : DevExpress.XtraEditors.XtraForm
    {
        List<LogEntity> LogList = new List<LogEntity>();
        public MainForm()
        {
            InitializeComponent();

            Type dgvType = dgv_contextList.GetType();
            var propertyInfo = dgvType.GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | BindingFlags.NonPublic);
            propertyInfo.SetValue(dgv_contextList, true, null);
           


            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            var dialogResult = folderBrowserDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                Text = "Now Loading from :" + folderBrowserDialog.SelectedPath;
                AnalysisFolder(folderBrowserDialog.SelectedPath);
            }
        }

        private void AnalysisFolder(string path)
        {
            var fileList = Directory.GetFiles(path).ToList();
            var fileListSorted = fileList.OrderBy(x => int.Parse(x.Split('.')[1]));
            List<StringLog> AllLogs = new List<StringLog>();
            int lineID = 0;
            foreach (string fileName in fileListSorted)
            {
                using (var fileStream = File.OpenRead(fileName))
                using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true))
                {
                    string line;
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        AllLogs.Add(new StringLog()
                        {
                            id = lineID,
                            content = line
                        });
                        lineID++;
                    }
                }
            }

            var allRequestLine = AllLogs.FindAll(log => log.content.Contains(", REQUEST,"));
            foreach (StringLog requestLine in allRequestLine)
            {
                AllLogs.RemoveAll(log => log.id == requestLine.id);
                LogEntity logEntity = new LogEntity();
                logEntity.intermediateLogs = new List<IntermediateLog>();

                var splitedRequestLine = requestLine.content.Split(',');
                string context = splitedRequestLine[0].Split(':')[1];
                logEntity.BeginTime = DateTime.Parse(splitedRequestLine[2]);
                logEntity.Context = context;
                logEntity.Url = splitedRequestLine[3].Replace("url:", "");

                logEntity.Parameter = requestLine.content.Split(new String[] { "params:null, body:" }, StringSplitOptions.RemoveEmptyEntries)[1];

                var contextLogs = AllLogs.FindAll(log => log.content.Contains(context));
                if (contextLogs.Count > 0)
                {
                    var responseLine = contextLogs.Find(log => log.content.Contains(", RESPONSE,"));
                    if (responseLine != null)
                    {
                        logEntity.elasped = int.Parse(responseLine.content.Split(',')[2]);
                        logEntity.Response = responseLine.content.Split(new String[] { "RESPONSE, " + logEntity.elasped + ", " }, StringSplitOptions.RemoveEmptyEntries)[1];
                    }
                }
                foreach (StringLog contextLog in contextLogs)
                {
                    AllLogs.RemoveAll(log => log.id == contextLog.id);
                    var splitedcontextLogs = contextLog.content.Split(',');
                    IntermediateLog intermediate = new IntermediateLog();
                    intermediate.Type = splitedcontextLogs[1];
                    intermediate.content = splitedcontextLogs[2];
                    logEntity.intermediateLogs.Add(intermediate);
                }
                LogList.Add(logEntity);
            }
            dgv_contextList.DataSource = LogList;
        }
    }
}